"""
订单管理模块 - 管理交易订单的生命周期
"""

import logging
from typing import Dict, List, Any, Optional
from datetime import datetime, timedelta
from enum import Enum

from trading.futu_trader import FutuTrader


class OrderStatus(Enum):
    """订单状态枚举"""
    PENDING = "待提交"
    SUBMITTED = "已提交"
    FILLED = "已成交"
    CANCELLED = "已撤销"
    REJECTED = "已拒绝"
    FAILED = "失败"


class OrderType(Enum):
    """订单类型枚举"""
    BUY = "买入"
    SELL = "卖出"


class Order:
    """订单对象"""
    
    def __init__(self, code: str, quantity: int, order_type: OrderType, 
                 price: float = None, order_id: str = None):
        self.order_id = order_id or f"ORDER_{datetime.now().strftime('%Y%m%d%H%M%S%f')}"
        self.code = code
        self.quantity = quantity
        self.order_type = order_type
        self.price = price  # None表示市价单
        self.status = OrderStatus.PENDING
        self.create_time = datetime.now()
        self.submit_time = None
        self.fill_time = None
        self.fill_price = None
        self.fill_quantity = 0
        self.message = ""
        
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            "order_id": self.order_id,
            "code": self.code,
            "quantity": self.quantity,
            "order_type": self.order_type.value,
            "price": self.price,
            "status": self.status.value,
            "create_time": self.create_time.isoformat(),
            "submit_time": self.submit_time.isoformat() if self.submit_time else None,
            "fill_time": self.fill_time.isoformat() if self.fill_time else None,
            "fill_price": self.fill_price,
            "fill_quantity": self.fill_quantity,
            "message": self.message
        }
    
    def __str__(self):
        price_str = f"@{self.price}" if self.price else "@市价"
        return f"{self.order_type.value} {self.code} {self.quantity}股{price_str} [{self.status.value}]"


class OrderManager:
    """订单管理器"""
    
    def __init__(self, config_manager, futu_trader: FutuTrader):
        """
        初始化订单管理器
        Args:
            config_manager: 配置管理器
            futu_trader: 富途交易接口
        """
        self.config_manager = config_manager
        self.futu_trader = futu_trader
        self.logger = logging.getLogger(__name__)
        
        # 订单存储
        self.orders: Dict[str, Order] = {}
        self.order_history: List[Order] = []
        
        # 自动交易设置
        self.auto_trading_enabled = False
        self.trading_interval = 5  # 交易间隔秒数
        self.last_trade_time = None
        
        self.logger.info("订单管理器初始化完成")
    
    def create_buy_order(self, code: str, quantity: int, price: float = None) -> Order:
        """
        创建买入订单
        Args:
            code: 股票代码
            quantity: 买入数量
            price: 买入价格，None为市价
        Returns:
            订单对象
        """
        order = Order(code, quantity, OrderType.BUY, price)
        self.orders[order.order_id] = order
        
        self.logger.info(f"创建买入订单: {order}")
        return order
    
    def create_sell_order(self, code: str, quantity: int, price: float = None) -> Order:
        """
        创建卖出订单
        Args:
            code: 股票代码
            quantity: 卖出数量  
            price: 卖出价格，None为市价
        Returns:
            订单对象
        """
        order = Order(code, quantity, OrderType.SELL, price)
        self.orders[order.order_id] = order
        
        self.logger.info(f"创建卖出订单: {order}")
        return order
    
    def submit_order(self, order: Order) -> bool:
        """
        提交订单
        Args:
            order: 订单对象
        Returns:
            提交是否成功
        """
        try:
            if order.status != OrderStatus.PENDING:
                self.logger.warning(f"订单状态不正确，无法提交: {order}")
                return False
            
            # 检查交易间隔
            if not self.check_trading_interval():
                order.status = OrderStatus.FAILED
                order.message = "交易间隔限制"
                self.logger.warning(f"交易间隔限制，订单提交失败: {order}")
                return False
            
            # 调用交易接口
            if order.order_type == OrderType.BUY:
                result = self.futu_trader.buy_stock(
                    order.code, order.quantity, order.price
                )
            else:
                result = self.futu_trader.sell_stock(
                    order.code, order.quantity, order.price
                )
            
            if result.get("success"):
                order.status = OrderStatus.SUBMITTED
                order.submit_time = datetime.now()
                order.message = result.get("message", "")
                
                # 更新最后交易时间
                self.last_trade_time = datetime.now()
                
                # 记录到配置管理器
                self.config_manager.add_history_record(
                    f"提交订单-{order.order_type.value}",
                    f"{order.code} {order.quantity}股",
                    "success"
                )
                
                self.logger.info(f"✅ 订单提交成功: {order}")
                return True
            else:
                order.status = OrderStatus.REJECTED
                order.message = result.get("message", "未知错误")
                
                self.logger.error(f"❌ 订单提交失败: {order}, 原因: {order.message}")
                return False
                
        except Exception as e:
            order.status = OrderStatus.FAILED
            order.message = f"提交异常: {e}"
            
            self.logger.error(f"订单提交异常: {order}, 异常: {e}")
            return False
    
    def cancel_order(self, order_id: str) -> bool:
        """
        撤销订单
        Args:
            order_id: 订单ID
        Returns:
            撤销是否成功
        """
        try:
            order = self.orders.get(order_id)
            if not order:
                self.logger.error(f"订单不存在: {order_id}")
                return False
            
            if order.status not in [OrderStatus.SUBMITTED]:
                self.logger.warning(f"订单状态不允许撤销: {order}")
                return False
            
            # 调用交易接口撤单
            result = self.futu_trader.cancel_order(order_id)
            
            if result.get("success"):
                order.status = OrderStatus.CANCELLED
                order.message = result.get("message", "订单已撤销")
                
                self.logger.info(f"✅ 订单撤销成功: {order}")
                return True
            else:
                order.message = f"撤销失败: {result.get('message', '未知错误')}"
                self.logger.error(f"❌ 订单撤销失败: {order}")
                return False
                
        except Exception as e:
            self.logger.error(f"撤销订单异常: {e}")
            return False
    
    def get_order(self, order_id: str) -> Optional[Order]:
        """获取订单"""
        return self.orders.get(order_id)
    
    def get_active_orders(self) -> List[Order]:
        """获取活跃订单（未完成的订单）"""
        active_statuses = [OrderStatus.PENDING, OrderStatus.SUBMITTED]
        return [order for order in self.orders.values() 
                if order.status in active_statuses]
    
    def get_completed_orders(self) -> List[Order]:
        """获取已完成订单"""
        completed_statuses = [OrderStatus.FILLED, OrderStatus.CANCELLED, 
                            OrderStatus.REJECTED, OrderStatus.FAILED]
        return [order for order in self.orders.values() 
                if order.status in completed_statuses]
    
    def get_all_orders(self) -> List[Order]:
        """获取所有订单"""
        return list(self.orders.values())
    
    def auto_trade_signal(self, signal_type: str, code: str, quantity: int = 100) -> bool:
        """
        自动交易信号处理
        Args:
            signal_type: 信号类型 ("BUY" 或 "SELL")
            code: 股票代码
            quantity: 交易数量
        Returns:
            处理是否成功
        """
        try:
            # 检查是否启用自动交易
            if not self.config_manager.get('trading.auto_trade', False):
                self.logger.info(f"自动交易未启用，忽略信号: {signal_type} {code}")
                return False
            
            # 验证交易配置
            if not self.futu_trader.validate_trading_config():
                self.logger.error("交易配置验证失败")
                return False
            
            # 创建订单
            if signal_type.upper() == "BUY":
                order = self.create_buy_order(code, quantity)
            elif signal_type.upper() == "SELL":
                order = self.create_sell_order(code, quantity)
            else:
                self.logger.error(f"未知信号类型: {signal_type}")
                return False
            
            # 提交订单
            success = self.submit_order(order)
            
            if success:
                self.logger.info(f"🤖 自动交易信号处理成功: {signal_type} {code}")
            else:
                self.logger.error(f"🤖 自动交易信号处理失败: {signal_type} {code}")
            
            return success
            
        except Exception as e:
            self.logger.error(f"自动交易信号处理异常: {e}")
            return False
    
    def check_trading_interval(self) -> bool:
        """检查交易间隔限制"""
        if not self.last_trade_time:
            return True
        
        interval = self.config_manager.get('trading.trade_interval', 5)
        elapsed = (datetime.now() - self.last_trade_time).total_seconds()
        
        return elapsed >= interval
    
    def cleanup_old_orders(self, days: int = 7):
        """清理旧订单（移到历史记录）"""
        try:
            cutoff_time = datetime.now() - timedelta(days=days)
            old_orders = []
            
            for order_id, order in list(self.orders.items()):
                if (order.create_time < cutoff_time and 
                    order.status in [OrderStatus.FILLED, OrderStatus.CANCELLED, 
                                   OrderStatus.REJECTED, OrderStatus.FAILED]):
                    old_orders.append(order)
                    del self.orders[order_id]
            
            # 添加到历史记录
            self.order_history.extend(old_orders)
            
            # 限制历史记录数量
            max_history = 1000
            if len(self.order_history) > max_history:
                self.order_history = self.order_history[-max_history:]
            
            if old_orders:
                self.logger.info(f"清理旧订单 {len(old_orders)} 个")
            
        except Exception as e:
            self.logger.error(f"清理旧订单失败: {e}")
    
    def get_order_statistics(self) -> Dict[str, Any]:
        """获取订单统计信息"""
        try:
            all_orders = self.get_all_orders()
            
            stats = {
                "total_orders": len(all_orders),
                "pending_orders": len([o for o in all_orders if o.status == OrderStatus.PENDING]),
                "submitted_orders": len([o for o in all_orders if o.status == OrderStatus.SUBMITTED]),
                "filled_orders": len([o for o in all_orders if o.status == OrderStatus.FILLED]),
                "cancelled_orders": len([o for o in all_orders if o.status == OrderStatus.CANCELLED]),
                "failed_orders": len([o for o in all_orders if o.status in [OrderStatus.REJECTED, OrderStatus.FAILED]]),
                "buy_orders": len([o for o in all_orders if o.order_type == OrderType.BUY]),
                "sell_orders": len([o for o in all_orders if o.order_type == OrderType.SELL]),
                "last_trade_time": self.last_trade_time.isoformat() if self.last_trade_time else None,
                "auto_trading_enabled": self.config_manager.get('trading.auto_trade', False)
            }
            
            return stats
            
        except Exception as e:
            self.logger.error(f"获取订单统计失败: {e}")
            return {}
    
    def export_orders(self, file_path: str) -> bool:
        """导出订单到文件"""
        try:
            import json
            
            orders_data = {
                "export_time": datetime.now().isoformat(),
                "orders": [order.to_dict() for order in self.get_all_orders()],
                "statistics": self.get_order_statistics()
            }
            
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(orders_data, f, indent=2, ensure_ascii=False)
            
            self.logger.info(f"订单数据已导出: {file_path}")
            return True
            
        except Exception as e:
            self.logger.error(f"导出订单失败: {e}")
            return False
